<?php
namespace app\api\controller;

use app\api\model\BaseModel;
use ethtool\Callback;
use ethtool\Credential;
use phpseclib\Math\BigInteger;
use think\Controller;
use think\Session;
use think\Db;
use Elliptic\EC;
use Web3\Contract;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
use Web3\Utils;
use Web3\Web3;
use xtype\Ethereum\Client as EthereumClient;
use kornrunner\Keccak;


class Timing extends Controller{
    protected  $web3;
    public function __construct(){
        parent::__construct();
        vendor("./hubwiz/ethtool/src/Callback");
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    //获取订单
    public function setTrans()
    {
        $client = new EthereumClient('https://mainnet.infura.io/v3/8234397b5aa1450d8a53107bbaf6c519');
        for ($i=0;$i<10;$i++)
        {
            //$blockNumber=$client->request("eth_blockNumber");
            $block=Db::name("block")->where("id",1)->find();
            $blockNumber=$block["block"];//
            $result=$client->request("eth_getBlockByNumber",[$this->to16($blockNumber),true]);
            $error=0;
            if($result!=null)
            {

                if(!empty($result->transactions)) {
                    Db::startTrans();
                    foreach ($result->transactions as $k => $val) {

                        if($this->to10($val->value)==0)
                        {
                            // Db::rollback();
                            continue;
                        }
                        $ethereum_log=Db::name("ethereum_log")->where("hash",$val->hash)->find();
                        if(!empty($ethereum_log))
                        {
                            //Db::rollback();
                            continue;
                        }
                        $userInfo = Db::name("user")->where("xst_address", $val->to)->find();
                        if (!empty($userInfo))
                        {
                            $res=changeBalance($userInfo["id"],"eth",1,$this->to10($val->value)/1000000000000000000,8,"充值",3);
                            $recharge=array(
                                "user_id"=>$userInfo["id"],
                                "my_wallet"=>$val->from,
                                "recharge_price"=>$this->to10($val->value)/1000000000000000000,
                                "recharge_wallet"=>$val->to,
                                "status"=>1,
                                "create_time"=>time()
                            );
                            $res1=Db::name("recharge")->insert($recharge);
                            $data=array(
                                "from"=>$val->from,
                                "to"=>$val->to,
                                "value"=>$val->value,
                                "hash"=>$val->hash,
                                "uid"=>$userInfo["id"],
                                "create_time"=>time()
                            );
                            $res2=Db::name("ethereum_log")->insert($data);

                            if($res&&$res1&&$res2)
                            {
                                //Db::commit();
                                echo $val->to."-".time().",充值成功!\r\n";
                            }else{
                                //Db::rollback();
                                echo $val->to."-".time().",充值失败!\r\n";
                                $error++;
                            }
                        }else
                        {
                            //Db::rollback();
                        }
                    }
                    if($error==0)
                    {
                        echo "区块".$blockNumber."处理完成";
                        Db::name("block")->where("id",1)->update(["block"=>++$blockNumber]);
                        Db::commit();
                    }else{
                        Db::rollback();
                    }
                }else{
                    echo "区块".$blockNumber."交易为空";
                    Db::name("block")->where("id",1)->update(["block"=>++$blockNumber]);
                }
            }
        }
    }
    //转为16进制
    function to16($num)
    {
        return "0x".base_convert($num, 10, 16);
    }
    //转为10进制
    public function to10($num)
    {
        return hexdec(substr($num,2));
    }
    /**
     * <p>功能描述：hex地址转地址。</p>
     * <p>jl</p>
     * @param strHex
     * @since JDK1.8
     * <p>创建日期：2018/10/19 16:24。</p>
     * <p>更新日期:[日期YYYY-MM-DD][更改人姓名][变更描述]。</p>
     */
    public function hexToAddress($strHex) {
        if (strlen($strHex) > 42) {
            if ($strHex[0]== '0' && ($strHex[1] == 'X' || $strHex[1] == 'x')) {
                $strHex = substr($strHex,2);
            }
            $strHex = substr($strHex,24);
            return "0x" . $strHex;
        }
        return null;
    }
    /**
     * <p>功能描述：16进制转10进制整数。</p>
     * <p>jl</p>
     * @param strHex
     * @since JDK1.8
     * <p>创建日期：2018/10/19 15:55。</p>
     * <p>更新日期:[日期YYYY-MM-DD][更改人姓名][变更描述]。</p>
     */
    public function hexToBigInteger($trHex) {

        if (strlen($trHex) > 2) {
            if ($trHex[0]== '0' && ($trHex[1] == 'X' || $trHex[1] == 'x')) {
                $trHex = substr($trHex,2);
            }
            $bigInteger= new BigInteger($trHex, 16);
            return $bigInteger;
        }
        return null;
    }
  	//释放
    public function release()
    {
        Db::startTrans();
        set_time_limit(0);
        $data = Db::name('release')->where('starttime','<=',time())->where('endtime','>',time())->select();
        $num = count($data);
        $res = Db::name('date')->where('starttime','EGT',strtotime(date('Ymd')))->where('starttime','ELT',strtotime(date('Ymd'))+86400)->select();
        if($res)
        {
            echo "今日已释放";die;
        }
        $starttime = time();
        $i = 0;
        $j = 0;
        foreach ($data as $val)
        {
            $r = $this->execution($val['id'],$val['uid'],$val['release'],$val['releases'],$val['remaining'],$val['already'],$val['starttime']);
            if(!$r)
            {
                $i++;
            }else{
            	$j++;
            }
        }
        $endtime = time();
        //添加今日释放日志
        $data=[
            'starttime'=>$starttime,
            'endtime'=>$endtime,
            'num'=>$num,
            'execution'=>$j,
        ];
        $r = Db::name('date')->insert($data);
        if($i==0&&$r)
        {
            echo "释放成功";
            Db::commit();
        }else{
            echo "释放失败";
            Db::rollback();
        }
    }
    public function execution($id,$uid,$relesae,$releases,$remaining,$already,$starttime)
    {
        $r=array();
        //获取用户余额
        $user_info = Db::name('balance')->where('uid',$uid)->find();
        //修改用户循环币
        $r[] = Db::name('balance')->where('uid',$uid)->setInc('circulate',$relesae);
        $r[] = Db::name('balance')->where('uid',$uid)->setInc('circulation',$releases);
        //$r[] = Db::name('balance')->where('uid',$uid)->setDec('frozen',($relesae+$releases));
        //添加日志
        $data=[
            'uid'=>$uid,
            'balance_type'=>1,
            'balance'=>$relesae,
            'type'=>10,
            'createtime'=>time(),
            'sign'=>1,
            'before_balance'=>$user_info['circulate'],
            'later_balance'=>$user_info['circulate']+$relesae,
            'message'=>'订单释放获得'.$relesae,
        ];
        $r[] = Db::name('balance_log')->insert($data);
        $datas=[
            'uid'=>$uid,
            'balance_type'=>2,
            'balance'=>$releases,
            'type'=>10,
            'createtime'=>time(),
            'sign'=>1,
            'before_balance'=>$user_info['circulation'],
            'later_balance'=>$user_info['circulation']+$releases,
            'message'=>'订单释放获得'.$relesae,
        ];
        $r[] = Db::name('balance_log')->insert($datas);
        //添加释放日志
      	
        $datas=[
            'uid'=>$uid,
            'rid'=>$id,
            'num'=>$relesae+$releases,
            'createtime'=>time(),
        ];
        $r[] = Db::name('release_log')->insert($datas);
        //修改释放表
      	if((strtotime(date('Ymd'))-$starttime)/86400==120)
        {
            $status = 2;
        }else{
            $status=1;
        }
        $r[] = Db::name('release')->where('id',$id)->update([
            'remaining'=>($remaining-($relesae+$releases)),
            'already'=>($already+($relesae+$releases)),
          	'status'=>$status,
        ]);
        if(!in_array(false,$r)){
            return true;
        }else{
            return false;
        }
    }
  //行情存库
    public function changemarket(){
        $data = $this->curl_file_get_contents('https://dncapi.bqiapp.com/api/coin/web-coinrank?page=1&type=0&pagesize=30&webp=1');
		$res = json_decode($data, true);
      	foreach($res['data'] as $k => $v){
        	if($v['name'] == "ETH"){
              	Db::name('setting')->where('id','7')->update(['value'=>$v['current_price']]);
            }else{
            	continue;
            }
        }
        echo "数据更新成功";die;                                                      
      	dump(json_decode($data, true));die;
      	//更新价格ccy兑换hyc价格
        //$CCY_ZT = $this->curl_file_get_contents('https://kline.zbg.com/api/data/v1/ticker?marketId=447');
        $CCY_USDT = $this->curl_file_get_contents('https://kline.zbg.com/api/data/v1/ticker?marketId=330');
        //$CCY_ZTs = json_decode($CCY_ZT, true);
        $CCY_USDTs = json_decode($CCY_USDT, true);
//        if($CCY_USDTs['datas']['1'] > $CCY_ZTs['datas']['1']){
//            $money = $CCY_USDTs['datas']['1'];
//        }else{
//            
//        }
        $money = $CCY_USDTs['datas']['1']*6.8;
      echo $money;die;
        Db::name('setting')->where('id','7')->update(['value'=>$money]);
       
      	echo "数据更新成功";
    }
   /*
     *  php访问url路径，get请求
     */
    function curl_file_get_contents($durl){
        // header传送格式
        // 初始化
        $curl = curl_init();
        // 设置url路径
        curl_setopt($curl, CURLOPT_URL, $durl);
        // 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
        // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
        // CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // 不验证SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 执行
        $data = curl_exec($curl);
        // 打印请求头信息
        //echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
        // 关闭连接
        // 返回数据
        return $data;
    }
}
?>